<template>
  <!-- 挂账支付 -->
  <div class="jeecg-basic-table jeecg-basic-table-form-container">
    <a-form @keyup.enter.native="searchQuery">
      <a-row :gutter="8" type="flex">
        <a-col flex="135px">
          <a-form-item label="部门" :label-col="{ style: { width: '40px' } }" :wrapper-col="{ span: 18 }">
            <JDictSelectTag
              v-model:value="queryParam.ddlxIds"
              mode="multiple"
              dictCode="ddlxType@ddlxUser"
              placeholder="全部"
              :maxTagCount="0"
              :getPopupContainer="(node) => node.parentNode"
              :dropdownStyle="{ width: '120px', overflow: 'auto' }"
              :dropdownMatchSelectWidth="false"
            />
          </a-form-item>
        </a-col>

        <a-col flex="115px">
          <a-form-item label="状态" :label-col="{ style: { width: '40px' } }" :wrapper-col="{ span: 17 }">
            <a-select v-model:value="queryParam.stat" @change="statSelect" class="w80" placeholder="全部" :showArrow="false" :allowClear="true">
              <a-select-option value="2">经理</a-select-option>
              <a-select-option value="3">已审</a-select-option>
              <a-select-option value="9">回退</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>

        <a-col flex="350px">
          <a-form-item label="审批时间" :label-col="{ style: { width: '70px' } }" :wrapper-col="{ style: { width: '270px' } }">
            <a-date-picker
              v-model:value="queryParam.spsjBegin"
              :disabled-date="disabledStartDate"
              :disabled="begDateDisabled"
              valueFormat="YYYY-MM-DD"
              placeholder=""
              style="width: 123px"
            /> ~
            <a-date-picker
              v-model:value="queryParam.spsjEnd"
              :disabled-date="disabledEndDate"
              :disabled="begDateDisabled"
              valueFormat="YYYY-MM-DD"
              placeholder=""
              style="width: 123px"
            />
          </a-form-item>
        </a-col>

        <a-col flex="165px">
          <a-form-item label="订单" :label-col="{ style: { width: '40px' } }" :wrapper-col="{ span: 20 }">
            <a-input placeholder="" v-model:value="queryParam.orderId"></a-input>
          </a-form-item>
        </a-col>

        <a-col flex="250px">
          <a-form-item label="单位名称" :label-col="{ style: { width: '70px' } }" :wrapper-col="{ span: 20 }">
            <a-input placeholder="" v-model:value="queryParam.dwmc"></a-input>
          </a-form-item>
        </a-col>

        <a-col flex="115px">
          <a-form-item label="合并" :label-col="{ style: { width: '40px' } }" :wrapper-col="{ span: 17 }">
            <Switch 
              v-model:checked="showSelection" 
              @change="toggleSelection"
              checked-children="显示" 
              un-checked-children="隐藏" 
              default-checked
            />
          </a-form-item>
        </a-col>

        <a-col flex="auto" style="float:right; width:180px;">
          <span style="float: right;overflow: hidden;" class="table-page-search-submitButtons">
            <a-button type="primary" @click="searchQuery" preIcon="ant-design:search">查询</a-button>
            <a-button type="default" @click="searchReset" preIcon="ant-design:reload-outlined" style="margin-left: 8px" v-if="!showSelection">重置</a-button>
            <a-button type="default" color="error" @click="handelMerge" preIcon="ant-design:reload-outlined" style="margin-left: 8px" v-if="showSelection">提交</a-button>
          </span>
        </a-col>
      </a-row>
    </a-form>
  </div>

  <!-- table区域-begin -->
  <BasicTable @register="registerTable" ref="tableRef"  
    :onRowDbClick="handleDblclick" :onRowClick="handleClick" :rowSelection="rowSelection" :rowClassName="rowClassName"
    :loading="false" >
    <template #operation="{text, record}">
      <a-badge :color="statusColor(text, record)" :text="operateTim(text, record)" />
    </template>
  </BasicTable>
  <!-- table区域-end -->

  <!-- 表单区域-->
  <AccountFlowInterval @register="registerAccountFlowInterval" @success="handleSuccess"></AccountFlowInterval>
  <AccountFlowBatchPaymentModal @register="registerAccountFlowBatchPaymentModal" @success="handleSuccess"></AccountFlowBatchPaymentModal>
</template>

<script lang="ts" setup name="accountFlow-takePayment">
import {ref, computed, unref, reactive, toRaw, nextTick} from 'vue';
import {BasicTable, BasicColumn} from '/@/components/Table'
import {useModal} from '/@/components/Modal';
import {useListPage} from '/@/hooks/system/useListPage'
import {render} from "/@/utils/common/renderUtils";
import {takePayment} from "/@/views/full/account/types/accountflow.api";
import {useMessage} from '/@/hooks/web/useMessage';
import {useUserStore} from '/@/store/modules/user';
import {paymentSubmit} from "/@/views/full/account/types/accountBatch.api";
import moment from 'dayjs'
import JDictSelectTag from '/@/components/Form/src/jeecg/components/JDictSelectTag.vue';
import AccountFlowInterval from './modules/AccountFlowInterval.vue';
import AccountFlowBatchPaymentModal from './modules/AccountFlowBatchPaymentModal.vue';
import { Switch } from 'ant-design-vue';

const { createMessage: $message } = useMessage();
const userStore = useUserStore();

//初始化 -------------------------------------------------------------
//定义查询表单，查询条件
const queryParam = reactive({
  ddlxIds: '',
  stat: '2', //未审
  spsjBegin: '',
  spsjEnd: '',
  orderId: '',
  dwmc: '',
});

/* 日期参数 */
function disabledStartDate(beginDate) {
  const endDate = queryParam.spsjEnd
  if (!beginDate || !endDate) {
    return false
  }
  // true 禁用 false 可用
  beginDate = moment(beginDate).format('YYYY-MM-DD')
  return moment(beginDate).valueOf() > moment(endDate).valueOf();
}

function disabledEndDate(endDate) {
  const beginDate = queryParam.spsjBegin
  if (!endDate || !beginDate) {
    return false
  }
  endDate = moment(endDate).format('YYYY-MM-DD')
  return moment(beginDate).valueOf() > moment(endDate).valueOf();
}

//转账支付，审核状态为经理时，默认查询日期是； 其它状态
let begDateDisabled = ref(true);
let endDateDisabled = ref(true);
function statSelect(data) {
  //console.info("statSelect@@@", data)
  if (data == '2' || data == '') {
    queryParam.spsjBegin  = "";
    queryParam.spsjEnd    = "";
    begDateDisabled.value = true;
    endDateDisabled.value = true;
  } else {
    var today = moment().format('YYYY-MM-DD');
    queryParam.spsjBegin = today;
    queryParam.spsjEnd   = today;
    begDateDisabled.value = false;
    endDateDisabled.value = false;
  }
}

//订单列表
const statusFmt = ({text}: { text: any }) => {
  if (!text) {
    return
  }
  const color = text == '2' ? 'red' : text == '3' ? 'green' : 'blue';
  return render.renderTag(render.renderDict(text, 'accountStat'), color)
}

//操作人 2经理，3已审，9回退
const statusColor = (text, record) => {
  let color = '';
  if (record.stat == '2') {
    color = 'green'
  } else if(record.stat == '3') {
    color = 'magenta'
    text = record.shsj
  } else if(record.stat == '9') {
    color = '#999'
    text = record.spsj
  }

  if (!text) {
    color = "";
  }
  return color
}

//操作时间
const operateTim = (text, record) => {
  if (record.stat == "2") {
    text = record.shsj
  } else if (record.stat == "3" || record.stat == "9") {
    text = record.spsj || record.shsj
  }
  if (!text) {
    return "";
  } else {
    return moment(text).format("YYYY-MM-DD HH:mm");
  }
}

const operator = ({ text, record }) => {
  if (record.stat == "2") {
    text = record.shrName
  } else if (record.stat == "3" || record.stat == "9") {
    text = record.sprName || record.shrName
  }
  if (!text) {
    return "";
  } else {
    return text;
  }
};

const sffsFmt = ({text}: { text: any }) => {
  if (!text) {
    return
  }
  let color : String[] = ['', 'red', '', 'blue', 'purple', 'orange'];
  return render.renderTag(render.renderDict(text, 'sffsType'), color[text])
}

//订单列表 - 表头 , customRender: operator | slots: { customRender: 'operation' }
const columns: BasicColumn[] = [
  {title:"状态", align:"center", dataIndex:"stat", width: 40, customRender: statusFmt,},
  {title:"订单号", align:"center", dataIndex:"orderId", width: 90, className: "text-red-500"},
  {title:"部门", align:"center", dataIndex:"ddlx", width: 60, customRender:({text}) => render.renderDict(text, 'ddlxType') },
  {title:"单位名称", align:"left", dataIndex:"pathName", width: 160},
  {title:'方式', align: 'center', dataIndex: 'sffs', width: 45, customRender: sffsFmt},
  {title:"支出金额", align:"right", dataIndex:"fkje", width: 80, className: "text-green-500"},
  {title:"备注", align:"left", dataIndex:"bz", width: 180},
  {title:"提交人", align:"center", dataIndex:"realname", width: 55 },
  {title:"提交日期", align:"center", dataIndex:"lrsj", width: 100, format: "date|YYYY-MM-DD hh:mm" },
  {title:"审核人", align:"center", dataIndex:"shrName", width: 55},
  {title:"审核日期", align:"center", dataIndex:"shsj", width: 100, format: "date|YYYY-MM-DD hh:mm" },
]

//初始化 -------------------------------------------------------------
function searchQuery() {
  setProps({searchInfo:toRaw(queryParam)});
  reload();
}

function searchReset() {
  Object.assign(queryParam, {ddlxIds: '', stat: '2', orderId: '', dwmc: '', spsjBegin: '', spsjEnd: ''});
  showSelection.value = false;
  begDateDisabled.value = true;
  endDateDisabled.value = true;
  searchQuery();
}

function handleSummary(tableData: Recordable[]) {
  const res = getRawDataSource()
  if (res) {
    return getRawDataSource().summary;
  } else {
    return [];
  }
}

// 列表页面公共参数、方法
const {prefixCls, tableContext} = useListPage({
  designScope: 'accountFlow-takePayment',
  tableProps: {
    api: takePayment,
    columns: columns,
    showTableSetting: false,
    showIndexColumn: true,    //行号
    clickToRowSelect: true,   //点击选择
    showActionColumn: false,
    useSearchForm: false,
    showSummary: true,
    resizeHeightOffset: 40,
    summaryFunc: handleSummary,
    beforeFetch: (params) => Object.assign(params, unref(queryParam)),
  },
})

//注册table数据
const [registerTable, { reload, setProps, getRawDataSource, setSelectedRowKeys, redoHeight }] = tableContext;

//详细订单
const [registerAccountFlowInterval, {openModal: openAccountFlowInterval}] = useModal();

//双击行
function handleDblclick(record) {
  //openBusinessOrder(true, record.id);
  var params = Object.assign({}, queryParam)
  params['id'] = record.id
  params['type'] = 'takePayment'
  openAccountFlowInterval(true, params);
}

//单击行
let selectRows = reactive<any>({id: '', username: ''});
function handleClick(record) {
  selectRows.id = record.id
}

function rowClassName(record, index) {
  return record.id === selectRows.id ? 'row-selected' : '';
}

// ----------------------------------------------------------

// 控制勾选框显示状态
const showSelection   = ref(false);
const selectedRowKeys = ref<String[]>([]);
const selectedRows    = ref({});

// 表格实例（使用any兼容不同版本）
const tableRef = ref<any>(null);

// 动态计算勾选配置
const rowSelection = computed(() => {
  // 隐藏勾选框时返回 null 或 undefined
  if (!showSelection.value) {
    return null;
  }

  // 显示勾选框时的配置（支持复选框/单选框）
  return {
    type: 'checkbox', // 可选 'checkbox' 或 'radio'
    onChange: (keys: string[], rows: any[]) => {
      selectedRowKeys.value = keys
      selectedRows.value = rows
    },
    // 自定义勾选框属性（如禁用某些行）
    getCheckboxProps: (record: any) => ({
      // disabled: record.age > 30, // 禁用年龄大于30的行
      // value: record.id,
    }),
  };
});

// 开关状态变化时的回调（可选）
const toggleSelection = async (checked: boolean) => {
  selectedRowKeys.value = [];
  selectedRows.value = {};
  // 当开关关闭（隐藏勾选框）时，清空之前的选择
  if (!checked) {
    await nextTick();
    tableRef.value.setSelectedRowKeys([]);
  }
};

//合并支付 - 弹窗 2025-09-12 qindl
const [registerAccountFlowBatchPaymentModal, { openModal: openAccountFlowBatchPaymentModal }] = useModal();

//合并支付 - 提交
function handelMerge() {
  //1、获取被选中的行信息
  let rows = unref(selectedRows) || [];
  if (rows.length <= 1) {
    $message.warning('合并支付：最少需要选择2条数据！'); //请勾选不能为空！
    return false;
  }

  //2、判断选中的单位是否是同一家
  var pId = [], ids = '';
  for (var i = 0; i < rows.length; i++) {
    pId.push(rows[i].coopId);
    if (i == 0) {
      ids = rows[i].id;
    } else {
      ids = ids + ',' + rows[i].id;
    }
  }

  let k = false;
  // && userStore.getTenant == 1 作集团系统设置
  if (pId.length > 0 && userStore.getTenant == 1) {
    pId = pId.sort();
    for (var i = 0; i < pId.length - 1; i++) {
      if (pId[i] != pId[i + 1]) {
        $message.warning('合并支付：只能选择相同的单位名称！');
        k = true;
        break;
      }
    }
  }

  if (k) {
    return false;
  }
  
  var params = Object.assign({}, queryParam);
  params['ids'] = ids;
  params['type'] = 'batchPayment';
  handleSubmit(params);

  //console.info(selectedRows)
  //openAccountFlowBatchPaymentModal(true, { ids });
}

//表单提交事件
async function handleSubmit(params) {
  paymentSubmit(params).then((res) => {
    if (res.success) {
      var params = Object.assign({}, queryParam)
      params['id'] = res.result
      params['type'] = 'takePayment'
      openAccountFlowInterval(true, params);
    } else {
      $message.error(res.message)
    }
  })
}

function handleSuccess(data) {
  if (data) {
    selectRows.id = data;
  } else {
    selectRows.id = '';
  }
  // 清理已勾选的数据
  selectedRowKeys.value = [];
  selectedRows.value = {};
  showSelection.value = false;
  searchQuery();
}

</script>
<style scoped>

</style>
